• 我们可以使用以前的C标准I/O库,它是一个可变成类的完美例子

.1 为啥要用输入输出流

当想确保一标准输入输出文件总是被安全地打开,被正确地关闭,而不依赖于用户是否调用了close()函数
#ifndef FILEECLAS_H_   //使用#pragma once可以实现同样的效果
#define FILEECLAS_H_
 
#include<stdio.h>
 
class file{
 
FILE* f;
public:
 
file(const char* fname,const char* mode="r");
~file();
FILE* fp();
};
#endif
在文件I/O函数中,为了取指针的值,可使用fp()访问函数。
这个成员函数的定义:
//FILEECLAS.CPP
#include<stdlib.h>
#include"..\5\fileclas.h"
 
file::file(const char* fname,const char* mode)
{
 
f=fopen(fname,mode);
if(f==null)
{
printf("%s:file not found\n",fname);
exit(1);
}
}
file ~flie(){  fclose(f);}
 
FILE* file::fp(){
return f;
}
}
就像常常做的一样,够着函数调用fopen(),但是它还检查结果,从而确保结果不是空的,如果f==null表示打开文件出错。
下面是驱动程序:
#include<assert.h>
#include"..\5\fileclas.h"
 
main(int argc,char*  argv[])
{
assert(argc==2);
file f(argv[1]);
#define B 100
char buf[B];
 
while(fgets(buf,B,f.fp())
      puts(buf);
 
}// flie automatically closed by destructor